package com.cssw.fyzb.core.mao.task;

import com.cssw.fyzb.core.model.mos.TaskStatMo;
import com.cssw.fyzb.core.mongo.MongoClient;
import com.cssw.fyzb.core.util.DocUtil;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author YangYiQun
 */
@Component
public class TaskStatMaoImpl implements TaskStatMao {

    @Autowired
    private MongoClient mongoClient;

    @Override
    public TaskStatMo findByUserId(Long userId) {
        Document doc = mongoClient.getCollection("task_stat")
                .find(new Document("userId", userId))
                .first();
        return DocUtil.decoce(doc, TaskStatMo.class);
    }

    @Override
    public void addViewTimeLong(Long userId, Integer viewDay, Integer viewTotalTime, Integer viewDayTime) {
        Document query = new Document();
        query.put("userId", userId);

        Document update = new Document();
        update.put("viewDay", viewDay);
        update.put("viewTotalTime", viewTotalTime);
        update.put("viewDayTime", viewDayTime);
        mongoClient.getCollection("task_stat").updateOne(query, new Document("$set", update));
    }

    public void save(TaskStatMo stat) {
        mongoClient.getCollection("task_stat")
                .insertOne(DocUtil.encode(stat));
    }

    @Override
    public void update(TaskStatMo taskStatMo) {
        Document query = new Document();
        query.put("userId", taskStatMo.getUserId());

        mongoClient.getCollection("task_stat").updateOne(query, new Document("$set",
                DocUtil.encode(taskStatMo)));
    }
}
